<?php
class PropertyController extends MainController implements ControllerInterface {

	public $tableConfig = array(
		'property_table' => array(
			'o' => array(
				'id' => 'property.id_property',
				'name' => 'property_description.description',
				'position' => 'property_group.position ASC, property.position',
				'_' => 'position'
			),
			'v' => 'rosnaco',
			't' => 10
		),
		'property_group_table' => array(
			'o' => array(
				'id' => 'property_group.id_property_group',
				'name' => 'property_group_description.description',
				'position' => 'property_group.position',
				'_' => 'position'
			),
			'v' => 'rosnaco',
			't' => 20
		)
	);


	public function preDispatch($param) {
		$this->RunShared('Auth', array());
		$this->Run($param);
		
		$this->smarty->assign('param_from_url',$param);
		$this->smarty->assign('languages',LanguageDAL::GetResult(LanguageDAL::GetDalDataobj(array('sortBy' => 'id_language ASC'))));
		$this->smarty->assign('categories',CategoryDAL::getAdminCategoryTree());
	}

	public function postDispatch($param) {
		
		
	}

	public function IndexAction($param) {
		$lang = Registry::Get('default_language_id');
		$list = PropertyDAL::GetResult(PropertyDAL::GetDalDataObj(array(
			'tableData' => $this->tableParams['property_table'],
			'join' => array(
				'PropertyDescription' => ' LEFT JOIN property_description ON(property.id_property = property_description.id_property AND property_description.id_language = '.Registry::Get('default_language_id').')',
				'PropertyGroup' => ' LEFT JOIN property_group ON(property.id_property_group = property_group.id_property_group)',
				'PropertyGroupDescription' => ' LEFT JOIN property_group_description ON(property_group_description.id_property_group = property_group.id_property_group AND property_group_description.id_language = '.Registry::Get('default_language_id').')'
			)
		)));
		$count = PropertyDAL::GetResult(PropertyDAL::GetDalDataObj(array(
			'count' => true
			)));

		$this->smarty->assign('list',$list);
		$this->smarty->assign('c',$count);


		$list2 = PropertyGroupDAL::GetDalDataObj(array(
			'tableData' => $this->tableParams['property_group_table'],
			'join' => array(
				'PropertyGroupDescription' => ' LEFT JOIN property_group_description ON(property_group.id_property_group = property_group_description.id_property_group AND property_group_description.id_language = '.Registry::Get('default_language_id').')'
			)
		));
		$list2->setLimit(1000);
		$list2 = PropertyGroupDAL::GetResult($list2);
		$count2 = PropertyGroupDAL::GetResult(PropertyGroupDAL::GetDalDataObj(array(
			'count' => true
			)));

		$this->smarty->assign('list2',$list2);
		$this->smarty->assign('c2',$count2);
	}

	public function AddGroupAction($param) {
		if(Request::IsPost()) {
			$propertyGroup = new PropertyGroup();
			$propertyGroup->setPosition(PropertyGroupDAL::getNextPosition());

			$id = PropertyGroupDAL::Insert($propertyGroup->getDalDataObj());
			$data = Request::GetAllPost();
			if(isset($data['description']) && is_array($data['description'])) {
				foreach(array_keys($data['description']) AS $id_language) {
					$propertyGroupDescription = new PropertyGroupDescription();
					$propertyGroupDescription->setIdLanguage($id_language);
					$propertyGroupDescription->setIdPropertyGroup($id);
					$propertyGroupDescription->setDescription($data['description'][$id_language]);
					PropertyGroupDescriptionDAL::Insert($propertyGroupDescription->getDalDataObj());
				}
			}

			$this->addRedirect(Router::GenerateUrl('propertyIndex',array('property' => 'Index')),0);
		}
	}

	public function RemoveGroupAction($param) {
		$this->setNoRender();
		$imageMap = PropertyGroupDAL::GetResult(PropertyGroupDAL::GetDalDataObj(array('condition' => array('id_property_group' => array($param['id'])))));

		$id = 0;

		foreach($imageMap AS $item) {

			PropertyGroupDAL::Delete($item->getDalDataObj());
		}

		$this->addRedirect(Router::Generateurl('propertyIndex',array('property' => 'index')),0);
	}

	public function EditGroupAction($param) {
		$obj = array_pop(PropertyGroupDAL::GetResult(PropertyGroupDAL::GetDalDataObj(array('condition' => array('id_property_group' => array($param['id']))))));
		$this->smarty->assign('obj',$obj);

		if(Request::IsPost()) {
			$data = Request::GetAllPost();
			if(isset($data['description']) && is_array($data['description'])) {
				foreach(array_keys($data['description']) AS $id_language) {
					$propertyGroupDescription = $obj->getDescription($id_language);
					$propertyGroupDescription->setIdLanguage($id_language);
					$propertyGroupDescription->setDescription($data['description'][$id_language]);
					PropertyGroupDescriptionDAL::Save($propertyGroupDescription->getDalDataObj());
				}
			}

			$this->addRedirect(Router::GenerateUrl('propertyIndex',array('property' => 'Index')),0);
		}
	}

	public function AddAction($param) {
		$list = PropertyGroupDAL::GetResult(PropertyGroupDAL::GetDalDataObj(array(
			'tableData' => $this->tableParams['property_group_table'],
			'join' => array(
				'PropertyGroupDescription' => ' LEFT JOIN property_group_description ON(property_group.id_property_group = property_group_description.id_property_group AND property_group_description.id_language = '.Registry::Get('default_language_id').')'
			)
		)));
		$this->smarty->assign('groups',$list);

		if(Request::IsPost()) {
			$data = Request::GetAllPost();

			$totalValuesStrlen = 0;

			foreach($data['property_value'] AS $type => $shit) {
				foreach($shit AS $value)
					$totalValuesStrlen += strlen($value);
			}

			$property = new Property();
			$property->setIdCategory($data['id_category']);
			$property->setIdPropertyGroup($data['id_property_group']);
			$property->setActive($data['active']);
			$property->setDate(date('Y-m-d G:i:s'));
			$property->setShowInFilters($data['show_in_filters']);
			$property->setShowInUser($data['show_in_user']);
			$property->setShowInSearch($data['show_in_search']);
			$property->setShowInList($data['show_in_list']);
			$property->setPosition(PropertyDAL::getNextPosition($data['id_property_group']));
			$property->setHasDefaultValues($totalValuesStrlen>0?1:0);
			$property->setType($data['type']);
			$property->setWeight($data['weight']);

			$id = PropertyDAL::Insert($property->getDalDataObj());

			foreach(array_keys($data['property_value'][0]) AS $key) {
				if(strlen($data['property_value'][0][$key]) + strlen($data['property_value'][1][$key]) == 0)
					continue;

				$propertyValue = new PropertyValue();
				$propertyValue->setIdProperty($id);
				$propertyValue->setType(0);
				$propertyValue->setIdProduct('NULL');
				$propertyValue->setParent('NULL');
				$propertyValue->setPrepend($data['property_prepend'][0][$key]);
				$propertyValue->setAppend($data['property_append'][0][$key]);
				$propertyValue->setValue($data['property_value'][0][$key]);
				$propertyValue->setWeight($key);

				PropertyValueDAL::Insert($propertyValue->getDalDataObj());

				if($property->getType() == 1) {

					$propertyValue = new PropertyValue();
					$propertyValue->setIdProperty($id);
					$propertyValue->setType(1);
					$propertyValue->setIdProduct('NULL');
					$propertyValue->setParent('NULL');
					$propertyValue->setPrepend($data['property_prepend'][1][$key]);
					$propertyValue->setAppend($data['property_append'][1][$key]);
					$propertyValue->setValue($data['property_value'][1][$key]);
					$propertyValue->setWeight($key);

					PropertyValueDAL::Insert($propertyValue->getDalDataObj());

				}
			}

			if(isset($data['description']) && is_array($data['description'])) {
				foreach(array_keys($data['description']) as $id_language) {
					$propertyDescription = new PropertyDescription();
					$propertyDescription->setDescription($data['description'][$id_language]);
					$propertyDescription->setText(Request::GetPost('text_'.$id_language,false));
					$propertyDescription->setIdProperty($id);
					$propertyDescription->setIdLanguage($id_language);

					PropertyDescriptionDAL::Insert($propertyDescription->getDalDataObj());
				}
			}

			$this->addRedirect(Router::GenerateUrl('propertyIndex',array('property' => 'index')),0);
		}
	}

	public function RemoveAction($param) {
		$this->setNoRender();
		$imageMap = PropertyDAL::GetResult(PropertyDAL::GetDalDataObj(array('condition' => array('id_property' => array($param['id'])))));

		$id = 0;

		foreach($imageMap AS $item) {

			PropertyDAL::Delete($item->getDalDataObj());
		}

		$this->addRedirect(Router::Generateurl('propertyIndex',array('property' => 'index')),0);
	}

	public function EditAction($param) {
		$list = PropertyGroupDAL::GetResult(PropertyGroupDAL::GetDalDataObj(array(
			'tableData' => $this->tableParams['property_group_table'],
			'join' => array(
				'PropertyGroupDescription' => ' LEFT JOIN property_group_description ON(property_group.id_property_group = property_group_description.id_property_group AND property_group_description.id_language = '.Registry::Get('default_language_id').')'
			)
		)));
		$this->smarty->assign('groups',$list);

		$obj = array_pop(PropertyDAL::GetResult(PropertyDAL::GetDalDataObj(array('condition' => array('id_property' => array($param['id'])), 'limit' => 1))));
		$this->smarty->assign('obj',$obj);


		if(Request::IsPost()) {
			$data = Request::GetAllPost();

			$property = $obj;

			$id = $property->getId();

			$totalValuesStrlen = 0;

			$props = $property->getDefaultValues();
			$defaults = array();
			if(is_array($props))foreach($props AS $propsT)
				if(is_array($propsT))foreach($propsT AS $propsI)
					$defaults[] = $propsI;

			$highest_weight = 0;

			foreach($defaults AS $prop) {
				if(strlen($data['default_value'][$prop->getId()].$data['default_prepend'][$prop->getId()].$data['default_append'][$prop->getId()]) > 0) {
					$prop->setValue($data['default_value'][$prop->getId()]);
					$prop->setPrepend($data['default_prepend'][$prop->getId()]);
					$prop->setAppend($data['default_append'][$prop->getId()]);
					$prop->setWeight($data['default_weight'][$prop->getId()]);
					$highest_weight = $data['default_weight'][$prop->getId()] > $highest_weight?$data['default_weight'][$prop->getId()]:$highest_weight;
					PropertyValueDAL::Save($prop->getDalDataObj());
					$totalValuesStrlen += 1;
				}else{
					PropertyValueDAL::Delete($prop->getDalDataObj());
				}

			}

			foreach($data['property_value'] AS $type => $shit) {
				foreach($shit AS $value)
					$totalValuesStrlen += strlen($value);
			}

			if($property->getIdPropertyGroup() != $data['id_property_group']) {
				$property->setPosition(PropertyDAL::getNextPosition($data['id_property_group']));
			}
			$property->setIdCategory($data['id_category']);
			$property->setIdPropertyGroup($data['id_property_group']);
			$property->setActive($data['active']);
			$property->setDate(date('Y-m-d G:i:s'));
			$property->setShowInFilters($data['show_in_filters']);
			$property->setShowInUser($data['show_in_user']);
			$property->setShowInSearch($data['show_in_search']);
			$property->setShowInList($data['show_in_list']);
			$property->setHasDefaultValues($totalValuesStrlen>0?1:0);
			$property->setType($data['type']);
			$property->setWeight($data['weight']);

			PropertyDAL::Save($property->getDalDataObj());

			$highest_weight = $highest_weight == 0 ? 0 : $highest_weight + 1;

			foreach(array_keys($data['property_value'][0]) AS $key) {
				if(strlen($data['property_value'][0][$key]) + (isset($data['property_value'][1])?strlen($data['property_value'][1][$key]):0) == 0)
					continue;

				$propertyValue = new PropertyValue();
				$propertyValue->setIdProperty($id);
				$propertyValue->setType(0);
				$propertyValue->setIdProduct('NULL');
				$propertyValue->setParent('NULL');
				$propertyValue->setPrepend($data['property_prepend'][0][$key]);
				$propertyValue->setAppend($data['property_append'][0][$key]);
				$propertyValue->setValue($data['property_value'][0][$key]);
				$propertyValue->setWeight($highest_weight);

				PropertyValueDAL::Insert($propertyValue->getDalDataObj());
				if($property->getType() == 1) {
					
					$propertyValue = new PropertyValue();
					$propertyValue->setIdProperty($id);
					$propertyValue->setType(1);
					$propertyValue->setIdProduct('NULL');
					$propertyValue->setParent('NULL');
					$propertyValue->setPrepend($data['property_prepend'][1][$key]);
					$propertyValue->setAppend($data['property_append'][1][$key]);
					$propertyValue->setValue($data['property_value'][1][$key]);
					$propertyValue->setWeight($highest_weight);

					PropertyValueDAL::Insert($propertyValue->getDalDataObj());
				}

				$highest_weight++;
			}

			if(isset($data['description']) && is_array($data['description'])) {
				foreach(array_keys($data['description']) as $id_language) {
					$propertyDescription = $property->getDescription($id_language);
					$propertyDescription->setDescription($data['description'][$id_language]);
					$propertyDescription->setText(Request::GetPost('text_'.$id_language,false));
					$propertyDescription->setIdLanguage($id_language);

					PropertyDescriptionDAL::Save($propertyDescription->getDalDataObj());
				}
			}

			$this->addRedirect(Router::GenerateUrl('propertyIndex',array('property' => 'index')),0);
		}
	}

	public function ProductAction($param) {
		$obj = array_pop(ProductDAL::GetResult(ProductDAL::GetDalDataObj(array('condition' => array('id_product' => array($param['id'])),'limit' => 1))));
		$category = array_pop(CategoryDAL::GetResult(CategoryDAL::GetDalDataObj(array('condition' => array('id_category' => array($obj->getIdcategory()))))));
		$this->smarty->assign('obj',$obj);
		$this->smarty->assign('default_language_id',Registry::Get('default_language_id'));


		$res = PropertyDAL::GetResult(PropertyDAL::GetDalDataObj(array(
			'condition' => array(
				'id_category' => array(array('condition' => ' IN ', 'value' => sprintf('(%s)', implode(',',array($category->getId(),$category->getParent())))))
			),
			'join' => array(
				'PropertyDescription' => ' LEFT JOIN property_description ON(property.id_property = property_description.id_property AND property_description.id_language = '.Registry::Get('default_language_id').')',
				'PropertyGroup' => ' LEFT JOIN property_group USING(id_property_group)',
				'PropertyGroupDescription' => ' LEFT JOIN property_group_description ON(property_group.id_property_group = property_group_description.id_property_group AND property_group_description.id_language = '.Registry::Get('default_language_id').')'
			),
			'sortBy' => 'property_group.position ASC, property.position ASC',
		)));

		if(Request::IsPost()) {
			$data = Request::GetAllPost();

			$keys = array_keys($data['property_prepend']);
			sort($keys);
			
			$values = PropertyValueDAL::GetResult(PropertyValueDAL::GetDalDataObj(array(
				'condition' => array(
					'id_property_value' => array(array('condition' => ' IN ', 'value' => sprintf('(%s)',implode(',',$keys))))
				),
				'sortBy' => 'id_property_value ASC',
				'join' => array(
					'Property' => ' LEFT JOIN property USING(id_property)'
				)
			)));

			$duplicate = array();

			foreach($values AS $value) {
				if(!isset($data['property_value'][$value->getId()]))
						continue;
				
				$value->setPrepend($data['property_prepend'][$value->getId()]);
				$value->setAppend($data['property_append'][$value->getId()]);
				$value->setValue($data['property_value'][$value->getId()]);

				if(isset($data['property_parent'][$value->getId()]))
						$value->setParent($data['property_parent'][$value->getId()]);

				PropertyValueDAL::Save($value->getDalDataObj());

				if($value->getProperty()->getType() == 0) {
					$duplicate[$value->getIdProperty()] = $value->getId();
				}
			}


			if(count($duplicate) > 0) {
				$values = PropertyValueDAL::GetResult(PropertyValueDAL::GetDalDataObj(array(
					'condition' => array(
						'id_property' => array(array(
							'condition' => ' IN ',
							'value' => sprintf('(%s)',implode(',',array_keys($duplicate)))
						)),
						'type' => array(1),
						'id_product' => array($param['id'])
					)
				)));

				

				foreach($values AS $value) {

					$value->setPrepend($data['property_prepend'][$duplicate[$value->getIdProperty()]]);
					$value->setAppend($data['property_append'][$duplicate[$value->getIdProperty()]]);
					$value->setValue($data['property_value'][$duplicate[$value->getIdProperty()]]);

					if(isset($data['property_parent'][$value->getId()]))
							$value->setParent($data['property_parent'][$duplicate[$value->getIdProperty()]]);

					PropertyValueDAL::Save($value->getDalDataObj());

					unset($duplicate[$value->getIdProperty()]);
				}
				
				foreach($duplicate AS $idProperty => $value) {
					$newValue = new PropertyValue();
					$newValue->setIdProperty($idProperty);
					$newValue->setPrepend($data['property_prepend'][$value->getId()]);
					$newValue->setAppend($data['property_append'][$value->getId()]);
					$newValue->setValue($data['property_value'][$value->getId()]);

					if(isset($data['property_parent'][$value->getId()]))
						$newValue->setParent($data['property_parent'][$value->getId()]);
					else
						$newValue->setParent('NULL');

					PropertyValueDAL::Save($newValue->getDalDataObj());

				}


			}

			$this->addRedirect(Router::GenerateUrl('productIndex',array('Product' => 'Index')),0);
		}

		$this->smarty->assign('list',$res);
	}

	public function SwitchAction($param) {
		$this->setNoRender();

		$list = PropertyDAL::GetResult(PropertyDAL::GetDalDataObj(array(
			'condition' => array(
				'id_property' => array(
					array('condition' => ' IN ', 'value' => sprintf('(%s)',implode(',',array($param['id'],$param['id_2']))))
				)
			)
		)));
		$temp = 0;
		foreach($list AS $k=>$v) {
			if($temp == 0) {
				$temp = $v->getPosition();
				continue;
			}else{
				$list[$k-1]->setPosition($v->getPosition());
				PropertyDAL::Save($list[$k-1]->getDalDataObj());

				if($k == count($list) - 1) {
					$v->setPosition($temp);
					PropertyDAL::Save($v->GetDalDataObj());
				}

			}
		}

		$this->addRedirect(Router::GenerateUrl('propertyIndex',array('property' => 'index')),0);
	}
}